//
//  InvestmentDetailViewController.m
//  DianDangDai
//
//  Created by bhf on 2017/12/16.
//  Copyright © 2017年 bhf. All rights reserved.
//

#import "InvestmentDetailViewController.h"
#import "M13ProgressViewRing.h"
#import "InvestmentModel.h"
#import "TenderRecordController.h"
#import "HomePageDetailController.h"
@interface InvestmentDetailViewController ()
@property (nonatomic, strong) M13ProgressViewRing *ring;
@property (strong, nonatomic) IBOutlet UIView *detail;
@property (strong, nonatomic) IBOutlet UIView *record;
@property (nonatomic, strong) NSDictionary *dataDict;
@property (nonatomic, strong) InvestmentModel *model;
@property (nonatomic, strong) NSDictionary *JSONDict;
@property (nonatomic, strong) NSString *URL;
@end

@implementation InvestmentDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.backBarButtonItem = BarButtonItem;
    [self setupViewsTouch];
  
    [self requestData];
    // Do any additional setup after loading the view.
}

- (void)requestData {
    
    NSString *urlString = [NSString stringWithFormat:@"%@OPT=1007&bidId=%ld",API_LOGIN_URL_STRING,_id];
    [[CDHttpHelper defaultCDHttpHelper] get:urlString params:nil success:^(id responseObj)
    {
        
        NSDictionary *dict = [responseObj objectFromJSONData];
        NSLog(@"%@",dict);
        _JSONDict= dict;
        _dataDict = dict[@"bmap"];
        _URL = dict[@"info"][@"detailUrl"];
        _model = [InvestmentModel mj_objectWithKeyValues:_dataDict];
        [self setupTopView];
        [self setUpTime];
    } failure:^(NSError *error) {
        
    } showHUD:YES];
}



- (void)setupTopView {
    self.title = @"出借项目";
    __block float progress = [_dataDict[@"loanSchedule"] floatValue];
    NSLog(@"%f",progress/100);
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1/*延迟执行时间*/ * NSEC_PER_SEC));
    
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        _topView.layer.cornerRadius =_topView.width/2;
        _ring = [[M13ProgressViewRing alloc] initWithFrame:CGRectMake(5, 5, _topView.width-10, _topView.height-10)];
        [_ring setProgressRingWidth:3];
        [_ring setBackgroundRingWidth:3];
        [_ring setPrimaryColor:[UIColor colorWithHex:@"#ffcc00"]];
        [_ring setSecondaryColor:[UIColor colorWithHex:@"#efefef"]];
        [_ring setContent:@"项目进度"];
        [_topView addSubview:_ring];
        [_ring setProgress:progress/100 animated:NO];
    });
    
    NSNumberFormatter *formatter1 = [[NSNumberFormatter alloc]init];
    formatter1.numberStyle =NSNumberFormatterPercentStyle;
   
    _apr.text = [formatter1 stringFromNumber:[NSNumber numberWithDouble:_model.apr/100]];
    
    
    
    NSNumberFormatter *formatter2 = [[NSNumberFormatter alloc]init];
    formatter2.numberStyle =NSNumberFormatterCurrencyStyle;
    NSInteger money = _model.amount;
    NSInteger sy = _model.hasInvestedAmount;
    NSLog(@"%ld",sy);
    self.syMoney.text =[formatter2 stringFromNumber:[NSNumber numberWithInteger:money - sy] ];
    self.ammount.text = [formatter2 stringFromNumber:[NSNumber numberWithInteger:money] ];
    
    _state.text = [@"项目状态：" stringByAppendingString:_dataDict[@"strStatus"]];
    NSString *period;
    if (_model.period_unit == 1) {
        period = @"天";
    } else if (_model.period_unit == 0) {
        period = @"个月";
    } else if (_model.period_unit == -1) {
        period = @"年";
    }
    _lastTime.text = [NSString stringWithFormat:@"出借期限：%ld%@",_model.period,period];
    _type.text = _dataDict[@"repayment"];
    _qitou.text = [NSString stringWithFormat:@"起投金额：%@",_dataDict[@"minInvestAmount"]];
    
}
//字符是否为数字
- (BOOL)isPureInt:(NSString *)string{
    
    NSScanner *scan = [NSScanner scannerWithString:string];
    
    int value;
    
    return [scan scanInt:&value] && [scan isAtEnd];
    
}
- (void)setupViewsTouch {
    UITapGestureRecognizer *tapGesturRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    UITapGestureRecognizer *tapGesturRecognizer2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showDetail:)];
    [_detail addGestureRecognizer:tapGesturRecognizer2];
    [_record addGestureRecognizer:tapGesturRecognizer];
}
- (void)tapAction:(id)tap {
    UIStoryboard *board = [UIStoryboard storyboardWithName:@"Investment" bundle:[NSBundle mainBundle]];
    TenderRecordController *hpdc = [board instantiateViewControllerWithIdentifier:@"trvc"];
    
    NSMutableArray *dataArray = [NSMutableArray array];
    
    for (NSDictionary *dict in _JSONDict[@"toubiaoren"]) {
        TenderModel *model = [TenderModel mj_objectWithKeyValues:dict];
        [dataArray addObject:model];
    }
    hpdc.model = [NSMutableArray arrayWithArray:dataArray];
    [self showViewController:hpdc sender:self];
}

- (void)showDetail:(id)tap {
    
    UIStoryboard *board = [UIStoryboard storyboardWithName:@"HomePage" bundle:[NSBundle mainBundle]];
    HomePageDetailController *hpdc = [board instantiateViewControllerWithIdentifier:@"hpdc"];
    hpdc.hidesBottomBarWhenPushed = YES;
    hpdc.titleStr = @"项目详情";
    
    hpdc.filepath = [NSURL URLWithString:_URL];
    [self showViewController:hpdc sender:self];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setUpTime {
  
    __block long time1= [_dataDict[@"investExpireTime"] floatValue]; //倒计时时间
    NSNumber *num = [NSNumber numberWithLong:time1];
    NSString *str1=[NSString stringWithFormat:@"%@",num];
    
    int x=[[str1 substringToIndex:10] intValue];
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:x];
    
    NSTimeInterval secondsBetweenDates= [date timeIntervalSinceDate:[NSDate date]];
    
    __block long timeout = secondsBetweenDates;
 
    //创建一个日历牌对象
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(timeout<=0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            
            dispatch_async(dispatch_get_main_queue(), ^{
         
            
            });
            
        }else{
            
            //            int minutes = timeout / 60;
            
            NSCalendar *calender=[NSCalendar currentCalendar];
            //枚举保存日期的每一天
            
            NSCalendarUnit unitsave=NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
            
            //计算日期
            
            __block NSDateComponents *comTogether=[calender components:unitsave fromDate:[NSDate date] toDate:date options:0];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                NSString *newStr = [NSString stringWithFormat:@"%ld天%ld时%ld分%ld秒",comTogether.day,comTogether.hour,comTogether.minute,comTogether.second];
                NSString *temp =nil;
                NSMutableAttributedString *attrString;
                NSMutableAttributedString *attrString2 = [[NSMutableAttributedString alloc] init];
                UIFont *font;
                for(int i =0; i < [newStr length]; i++)
                    
                {
                    
                    temp = [newStr substringWithRange:NSMakeRange(i,1)];
                 
                    
                    if ([self isPureInt:temp]) {
                        font = [UIFont systemFontOfSize:22.0];
                        attrString = [[NSMutableAttributedString alloc] initWithString:temp];
                        [attrString addAttribute:NSFontAttributeName value:font range:[temp rangeOfString:temp]];
                    } else {
                        font = [UIFont systemFontOfSize:11.0];
                        attrString = [[NSMutableAttributedString alloc] initWithString:temp];
                        [attrString addAttribute:NSFontAttributeName value:font range:[temp rangeOfString:temp]];
                        [attrString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHex:@"#333333"] range:[temp rangeOfString:temp]];
                    }
                    [attrString2 appendAttributedString:attrString];
                }
          
                _time.attributedText = attrString2;
                
            });
            
            timeout--;
            
        }
        
    });
    
    dispatch_resume(_timer);
}

/**
 *
-----倒计时
*/

-(NSString *)getyyyymmdd {
    NSDate *now = [NSDate date];
    NSDateFormatter *formatDay = [[NSDateFormatter alloc] init];
    formatDay.dateFormat = @"yyyy-MM-dd";
    NSString *dayStr = [formatDay stringFromDate:now];
    return dayStr;
}

- (NSString *)returndate:(NSNumber *)num{
    
    NSString *str1=[NSString stringWithFormat:@"%@",num];
    
    int x=[[str1 substringToIndex:10] intValue];
    
    NSDate  *date1 = [NSDate dateWithTimeIntervalSince1970:x];
    
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc]init];
    
    [dateformatter setDateFormat:@"yyyy-MM-dd hh:mm"];
    
    return [dateformatter stringFromDate:date1];
    
}





/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
